<?php

class TabunganController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/template';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','create','historisimpanan','FormSimpanan','SimpananWajib','SaveTabungan','TambahSaldo','LaporanSimpanan','cetak_laporan_simpanan','Delete_Tabungan','InputPokok'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Lists all models.
	 */
	
	public function actionFormSimpanan(){
		$this->render('indexform');
	}
	
	
	public function actionSimpananWajib($id,$idx){
		
		if (isset($_GET['pageSize'])) {
			Yii::app()->user->setState('pageSize',(int)$_GET['pageSize']);
			unset($_GET['pageSize']);  // would interfere with pager and repetitive page size change
		}
		
		$criteria = new CDbCriteria;
		$criteria->condition="ID_ANGGOTA NOT IN (SELECT anggota.ID_ANGGOTA FROM anggota JOIN history_tabungan ON (anggota.ID_ANGGOTA=history_tabungan.ID_ANGGOTA) WHERE MONTH(TANGGAL_TRANSAKSI)=".$id." AND YEAR(TANGGAL_TRANSAKSI)=".$idx.")";
		
		$model = new Anggota('search');
		$model->unsetAttributes();  // clear any default values
		if (isset($_GET['Anggota'])) {
			$key = $_GET['Anggota'];
			$criteria->condition='ID_ANGGOTA NOT IN (SELECT anggota.ID_ANGGOTA FROM anggota JOIN history_tabungan ON (anggota.ID_ANGGOTA=history_tabungan.ID_ANGGOTA) WHERE MONTH(TANGGAL_TRANSAKSI)='.$id.' AND YEAR(TANGGAL_TRANSAKSI)='.$idx.') AND (NO_ANGGOTA LIKE "%'.$key['NO_ANGGOTA'].'%" OR NAMA LIKE "%'.$key['NAMA'].'%")';
		}
		
		$dataProvider = new CActiveDataProvider('Anggota', array(
						'criteria'      => $criteria,
						'pagination' => 
							array('pageSize'=> Yii::app()->user->getState('pageSize',Yii::app()->params['defaultPageSize']),
							),
						));
		
		$this->render('indexSimpanan', array(
			'dataProvider'  => $dataProvider,'model' => $model,'id'=>$id,'tahun'=>$idx
		));
		
	}
	
	
	public function actionSaveTabungan(){
		$keys = explode(',',$_POST["data"]);
		$i= 0;
		//var_dump($keys);
		while ($i<count($keys)){
			
			$model = new HistoryTabungan;
			$model->ID_ANGGOTA = $keys[$i];
			$model->TANGGAL_TRANSAKSI = $_POST["tahun"].'-'.$_POST["bulan"].'-01';
			
			$anggota = Anggota::model()->find("ID_ANGGOTA=".$model->ID_ANGGOTA);
			if ($anggota->STATUS_PEGAWAI == 1){
				$model->ID_SIMPANAN = 2;
				$simpanan_tetap = JenisSimpanan::model()->find('ID_SIMPANAN = 2');
				$model->JUMLAH = $simpanan_tetap->BESAR_SIMPANAN;
			}
			else if ($anggota->STATUS_PEGAWAI == 2){
				$model->ID_SIMPANAN = 3;
				$simpanan_tdk_tetap = JenisSimpanan::model()->find('ID_SIMPANAN = 3');
				$model->JUMLAH = $simpanan_tdk_tetap->BESAR_SIMPANAN;
			}
			
			//var_dump($model->attributes);
			
			if($model->save()){
				$tabungan = Tabungan::model()->find("ID_ANGGOTA=".$model->ID_ANGGOTA);
				if ($tabungan == null){
					$new_tabungan = new Tabungan; 
					$new_tabungan->ID_ANGGOTA = $model->ID_ANGGOTA; 
					$new_tabungan->TOTAL_TABUNGAN = $model->JUMLAH;
					
					$new_tabungan->save();
				}
				else {
					$tabungan->TOTAL_TABUNGAN = $tabungan->TOTAL_TABUNGAN + $model->JUMLAH;
					
					$tabungan->save();
				}
				
				$this->otomasiJurnal($model->TANGGAL_TRANSAKSI,$anggota->NAMA,$model->JUMLAH);
			}
			$i++;
		}
	}
	
	public function actionhistorisimpanan($id){
		$criteria = new CDbCriteria;
		$criteria->condition = "ID_ANGGOTA=".$id;
			if (isset($_REQUEST['sSearch']) && isset($_REQUEST['sSearch']{0})) {
				  
			 }

			$sort = new EDTSort('HistoryTabungan', array('TANGGAL_TRANSAKSI','JUMLAH'));
			 $sort->defaultOrder = array('TANGGAL_TRANSAKSI'=>CSort::SORT_DESC);
			 $pagination = new EDTPagination();
			 
			 $dataProvider = new CActiveDataProvider('HistoryTabungan', array(
				  'criteria'      => $criteria,
				  'pagination'    => $pagination,
				  'sort'          => $sort,
			 ));
			 
			$widget=$this->createWidget('ext.EDataTables.EDataTables', array(
			 'id'            => 'HistoryTabungan',
			 'dataProvider'  => $dataProvider,
			 'ajaxUrl'       => Yii::app()->getBaseUrl().'/index.php/Tabungan/historisimpanan',
			 'columns'       => array(
									array(
									'name'=>'TANGGAL_TRANSAKSI',
									'value'=>'date("d-m-Y",strtotime($data->TANGGAL_TRANSAKSI))',
									),
									array(
									'name'=>'JUMLAH',
									'value'=>'"Rp ".number_format($data->JUMLAH,2,",",".")',
									),
									/*
									array(
									'name'=>'KETERANGAN',
									'value'=>'($data->ID_SIMPANAN==null)?("Saldo"):(($data->ID_SIMPANAN==1)?("Simpanan Pokok"):("Simpanan Wajib"))',
									),
									*/
		array(
        'class'=>'ext.EDataTables.EButtonColumn',
		'template'=>'{delete}',
		'header'=>'Hapus Historis',
		'buttons'=>array(
					'delete'=>array(
			'label'=>'Hapus Histori',
'url'=>'Yii::app()->createUrl("Tabungan/Delete_Tabungan/".$data->ID_HISTORY_TABUNGAN."/"."'.$id.'")',
			'imageUrl'=>Yii::app()->request->baseUrl.'/images/grid/deleted.png',
									),
							),
        'deleteConfirmation'=>"js:'Hapus Histori Tabungan pada Tanggal  '+$(this).parent().parent().children(':first-child').text()+' dengan Jumlah '+$(this).parent().parent().children(':nth-child(2)').text()+' dari daftar?'",		),
								),
			'buttons' => array(
					// 'refresh' => null,
					'print' => null,
					'export' => null,
					'klaim' => array(
								 'label' => 'Kembali',
								 'text' => true,
								 'htmlClass' => 'refreshButton',
								 'icon' => 'ui-icon-document',
'callback' => 'js:function(){document.location.href = \''.Yii::app()->request->baseUrl.'/index.php/Tabungan/view/'.$id.'\';}',
								),
				)
			 
			));		
		
			if (!Yii::app()->getRequest()->getIsAjaxRequest()) {
				$this->render('index', array('widget' => $widget));
				return;
			} else {
			  echo json_encode($widget->getFormattedData(intval($_REQUEST['sEcho'])));
			  Yii::app()->end();
			}
	}
	
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$criteria = new CDbCriteria;
		$criteria->condition="ID_ANGGOTA=".$id;
			
			if (isset($_REQUEST['sSearch']) && isset($_REQUEST['sSearch']{0})) {
				  
			 }

			$sort = new EDTSort('Tabungan', array('anggota.NAMA','TOTAL_TABUNGAN'));
			 $sort->defaultOrder = 'ID_TABUNGAN';
			 $pagination = new EDTPagination();
			 
			 $dataProvider = new CActiveDataProvider('Tabungan', array(
				  'criteria'      => $criteria,
				  'pagination'    => $pagination,
				  'sort'          => $sort,
			 ));
			 
			$widget=$this->createWidget('ext.EDataTables.EDataTables', array(
			 'id'            => 'Tabungan',
			 'dataProvider'  => $dataProvider,
			 'ajaxUrl'       => Yii::app()->getBaseUrl().'/index.php/Tabungan/view',
			 'columns'       => array('anggota.NAMA',
								array(
									'name'=>'TOTAL_TABUNGAN',
									'value'=>'"Rp ".number_format($data->TOTAL_TABUNGAN,2,",",".")',
								),
								array('class'=>'ext.EDataTables.EButtonColumn',
												'header'=>'Historis Simpanan',
												'template'=>'{myButton}',
												'buttons'=>array(
														'myButton'=>array(
												'label'=>'Lihat Historis Simpanan',
												'url'=>'Yii::app()->createUrl("Tabungan/historisimpanan/".$data->ID_ANGGOTA)',
												'imageUrl'=>Yii::app()->request->baseUrl.'/images/grid/pencil-icon.png',
																		),
																),
												),
								),
			'buttons' => array(
					// 'refresh' => null,
					'print' => null,
					'export' => null,
					'saldo' => array(
								 'label' => 'Input Saldo',
								 'text' => true,
								 'htmlClass' => 'refreshButton',
								 'icon' => 'ui-icon-document',
'callback' => 'js:function(){document.location.href = \''.Yii::app()->request->baseUrl.'/index.php/Tabungan/TambahSaldo/'.$id.'\';}',
								),
					'pokok' => array(
								 'label' => 'Input Simpanan Pokok',
								 'text' => true,
								 'htmlClass' => 'refreshButton',
								 'icon' => 'ui-icon-document',
'callback' => 'js:function(){document.location.href = \''.Yii::app()->request->baseUrl.'/index.php/Tabungan/InputPokok/'.$id.'\';}',
								),
					'klaim' => array(
								 'label' => 'Kembali',
								 'text' => true,
								 'htmlClass' => 'refreshButton',
								 'icon' => 'ui-icon-document',
'callback' => 'js:function(){document.location.href = \''.Yii::app()->request->baseUrl.'/index.php/SimpanPinjam\';}',
								),
								)
			));		
		
			if (!Yii::app()->getRequest()->getIsAjaxRequest()) {
				$this->render('view', array('widget' => $widget));
				return;
			} else {
			  echo json_encode($widget->getFormattedData(intval($_REQUEST['sEcho'])));
			  Yii::app()->end();
			}
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Tabungan;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Tabungan']))
		{
			$model->attributes=$_POST['Tabungan'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->ID_TABUNGAN));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Tabungan']))
		{
			$model->attributes=$_POST['Tabungan'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->ID_TABUNGAN));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}
	
	public function actionDelete_Tabungan($id,$idx)
	{
		$history = HistoryTabungan::model()->find("ID_HISTORY_TABUNGAN=".$id);
		
		if($history->delete()){
			$tabungan = Tabungan::model()->find("ID_ANGGOTA=".$idx);
			$tabungan->TOTAL_TABUNGAN = $tabungan->TOTAL_TABUNGAN - $history->JUMLAH;
			
			if ($tabungan->save()){
				$this->redirect(array('historisimpanan','id'=>$idx));
			}
		}
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Tabungan('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Tabungan']))
			$model->attributes=$_GET['Tabungan'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}
	
	public function actionTambahSaldo($id)
	{
		$tabungan=Tabungan::model()->find('ID_ANGGOTA = '.$id);
		$history= new HistoryTabungan;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['HistoryTabungan']))
		{
			$history->ID_ANGGOTA = $id;
			$history->TANGGAL_TRANSAKSI = date('Y-m-d', strtotime($_POST['HistoryTabungan']['TANGGAL_TRANSAKSI']));
			$history->JUMLAH = $_POST['HistoryTabungan']['JUMLAH'];
			
			if($tabungan == null){
				$newtabungan = new Tabungan;
				$newtabungan->ID_ANGGOTA = $id;
				$newtabungan->TOTAL_TABUNGAN = $history->JUMLAH;
				
				$newtabungan->save();
			}
			else {
				$tabungan->TOTAL_TABUNGAN = $tabungan->TOTAL_TABUNGAN + $history->JUMLAH;
				
				$tabungan->save();
			}
			
			
			if($history->save())
				$this->redirect(array('view','id'=>$id));
		}

		$this->render('tambahsaldo',array(
			'model'=>$history,'id'=>$id
		));
	}
	
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Tabungan::model()->with('anggota')->find("ID_ANGGOTA=".$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='tabungan-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	public function actionLaporanSimpanan(){
		
		if(isset($_POST['tahun'])){
			$id = $_POST['tahun'];
			$model = HistoryTabungan::model()->findAll(array('condition'=>'YEAR(TANGGAL_TRANSAKSI)='.$id, 'group'=>'ID_ANGGOTA'));
			$data = array();
		foreach($model as $count){
			$model_count = HistoryTabungan::model()->findAll('YEAR(TANGGAL_TRANSAKSI)='.$id.' AND ID_ANGGOTA='.$count->ID_ANGGOTA);
			$pokok = 0; $wajib = 0;
			foreach($model_count as $model_member){
				
				$get_pokok = HistoryTabungan::model()->findAll('ID_ANGGOTA='.$count->ID_ANGGOTA.' AND ID_SIMPANAN = 1');
				
				if ($get_pokok != null){
					foreach($get_pokok as $gp){
					$pokok = $pokok+$gp->JUMLAH;
					}
				}
				
				if ($model_member->ID_SIMPANAN == 2){
					$wajib = $wajib+$model_member->JUMLAH;
				}
			}
			$datum['id'] = $count->ID_ANGGOTA;
			$datum['pokok'] = $pokok;
			$datum['wajib'] = $wajib;
			
			$data[]= $datum;
		}
	
			$objPHPExcel = new PHPExcel();
			$sheet = $objPHPExcel->setActiveSheetIndex(0);  
			
			 $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(10);
			 $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(35);
			 $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(30);
			 $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(25);
			 $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(25);
			 $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(25);
			
			
			$sheet->mergeCells('A1:F1')->setCellValue('A1', 'DAFTAR SIMPANAN ANGGOTA')->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
			$sheet->mergeCells('A2:F2')->setCellValue('A2', 'KOPERASI RUMAH SAKIT HAJI SURABAYA')->getStyle('A2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

			$sheet->mergeCells('A4:F4')->setCellValue('A4', 'PERIODE : JANUARI '.$id.' s/d DESEMBER '.$id )->getStyle('A4')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
			
			$sheet->getStyle("A1:A2")->applyFromArray(array("font" => array( "bold" => true, "size"=>18)));
			$sheet->getStyle("A4")->applyFromArray(array("font" => array( "bold" => true, "size"=>12)));
			$sheet->getStyle("A6:F6")->applyFromArray(array("font" => array( "bold" => true, "size"=>10)));
			$sheet->getStyle("D7:E7")->applyFromArray(array("font" => array( "bold" => true, "size"=>10)));
			
			// Add some data
			$sheet->mergeCells('A6:A7')->setCellValue('A6', 'NO.')->getStyle('A6')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
			$sheet->mergeCells('B6:B7')->setCellValue('B6', 'NAMA ANGGOTA')->getStyle('B6')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
			$sheet->mergeCells('C6:C7')->setCellValue('C6', "JUMLAH SIMPANAN TAHUN ".($id-1)." \r (Rp)")->getStyle('C6')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
			$sheet->mergeCells('D6:E6')->setCellValue('D6', "MUTASI SIMPANAN TAHUN $id")->getStyle('D6')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
			$sheet->setCellValue('D7', "POKOK \r (Rp)")->getStyle('D7')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
			$sheet->setCellValue('E7', "WAJIB \r (Rp)")->getStyle('E7')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
			$sheet->mergeCells('F6:F7')->setCellValue('F6', "JUMLAH TOTAL SIMPANAN \r (Rp)")->getStyle('F6')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
			
			$sheet->getStyle('A6')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
			$sheet->getStyle('B6')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
			$sheet->getStyle('C6')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
			$sheet->getStyle('D6')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
			$sheet->getStyle('E6')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
			$sheet->getStyle('F6')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
			
			$sheet->getStyle('A6')->getAlignment()->setWrapText(true);
			$sheet->getStyle('B6')->getAlignment()->setWrapText(true);
			$sheet->getStyle('C6')->getAlignment()->setWrapText(true);
			$sheet->getStyle('D6')->getAlignment()->setWrapText(true);
			$sheet->getStyle('E6')->getAlignment()->setWrapText(true);
			$sheet->getStyle('F6')->getAlignment()->setWrapText(true);
			
			$sheet->getStyle("A6:F6")->applyFromArray(array('borders' => array('allborders' => array('style' => PHPExcel_Style_Border::BORDER_THICK))));
			$sheet->getStyle("A7:F7")->applyFromArray(array('borders' => array('allborders' => array('style' => PHPExcel_Style_Border::BORDER_THICK))));
			
			$no = 1;$i = 8;
			foreach($data as $row){
				$model = Anggota::model()->find("ID_ANGGOTA=".$row['id']);
				$model_past = HistoryTabungan::model()->findAll('YEAR(TANGGAL_TRANSAKSI)='.($id-1).' AND ID_ANGGOTA='.$row['id']);
				$total_past = 0;
				foreach($model_past as $data_past){
					$total_past = $total_past + $data_past->JUMLAH;
				}

				$sheet->setCellValue('A'.$i, $no);
				$sheet->setCellValue('B'.$i, $model->NAMA);
				$sheet->setCellValue('C'.$i, $total_past)->getStyle('C'.$i)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1);
				$sheet->setCellValue('D'.$i, $row['pokok'])->getStyle('D'.$i)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1);
				$sheet->setCellValue('E'.$i, $row['wajib'])->getStyle('E'.$i)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1);
				$sheet->setCellValue('F'.$i, $total_past+$row['pokok']+$row['wajib'])->getStyle('F'.$i)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1);
				
				$sheet->getStyle("A".$i.":F".$i)->applyFromArray(array('borders' => array('allborders' => array('style' => PHPExcel_Style_Border::BORDER_THIN))));
				
				$no++;$i++;
			}
			
			// Save a xls file
			$filename = 'Laporan Simpanan Anggota Tahun '.$id;
			header('Content-Type: application/vnd.ms-excel');
			header('Content-Disposition: attachment;filename="'.$filename.'.xlsx"');
			header('Cache-Control: max-age=0');
			
			$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);

			$objWriter->save('php://output');
			unset($this->objWriter);
			unset($this->objWorksheet);
			unset($this->objReader);
			unset($this->objPHPExcel);
			exit();
		}
		$this->render('LaporanSimpanan');
	} 
	
	public function actioncetak_laporan_simpanan($id){
		$this->layout = 'none';
		$model = HistoryTabungan::model()->findAll(array('condition'=>'YEAR(TANGGAL_TRANSAKSI)='.$id, 'group'=>'ID_ANGGOTA'));
		
		foreach($model as $count){
			$model_count = HistoryTabungan::model()->findAll('YEAR(TANGGAL_TRANSAKSI)='.$id.' AND ID_ANGGOTA='.$count->ID_ANGGOTA);
			$pokok = 0; $wajib = 0;
			foreach($model_count as $model_member){
				
				$get_pokok = HistoryTabungan::model()->findAll('ID_ANGGOTA='.$count->ID_ANGGOTA.' AND ID_SIMPANAN = 1');
				
				if ($get_pokok != null){
					foreach($get_pokok as $gp){
					$pokok = $pokok+$gp->JUMLAH;
					}
				}
				
				if ($model_member->ID_SIMPANAN == 2){
					$wajib = $wajib+$model_member->JUMLAH;
				}
			}
			$datum['id'] = $count->ID_ANGGOTA;
			$datum['pokok'] = $pokok;
			$datum['wajib'] = $wajib;
			
			$data[]= $datum;
			
			
		}
		
		if($model == null){
			$this->redirect(array('LaporanSimpanan'));
		}
		else
		$this->render('cetak_laporan_simpanan',array('data'=>$data,'tahun'=>$id));
	}
	
	
	public function actionInputPokok($id)
	{
		$tabungan=Tabungan::model()->find('ID_ANGGOTA = '.$id);
		$history= new HistoryTabungan;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['HistoryTabungan']))
		{
			$history->ID_ANGGOTA = $id;
			$history->TANGGAL_TRANSAKSI = date('Y-m-d', strtotime($_POST['HistoryTabungan']['TANGGAL_TRANSAKSI']));
			$history->JUMLAH = $_POST['HistoryTabungan']['JUMLAH'];
			$history->ID_SIMPANAN = 1;
			
			if($tabungan == null){
				$newtabungan = new Tabungan;
				$newtabungan->ID_ANGGOTA = $id;
				$newtabungan->TOTAL_TABUNGAN = $history->JUMLAH;
				
				$newtabungan->save();
			}
			else {
				$tabungan->TOTAL_TABUNGAN = $tabungan->TOTAL_TABUNGAN + $history->JUMLAH;
				
				$tabungan->save();
			}
			
			
			if($history->save())
				$this->redirect(array('view','id'=>$id));
		}

		$this->render('inputpokok',array(
			'model'=>$history,'id'=>$id
		));
	}
	
	public function otomasiJurnal($tanggal,$nama,$jumlah){
		$otomasi = AkunOtomasi::model()->findByPk(2);
				
				$jurnal = new Jurnal;
				$last_jurnal = Jurnal::model()->find(array("order" => "ID_JURNAL DESC"));
				
				if ($last_jurnal->NO_JURNAL == null){
					$no_jurnal = 1;
				}
				else {
					$split = explode("-",$last_jurnal->NO_JURNAL);
					$no_jurnal = $split[1] + 1;
				}
				
				$jurnal->NO_JURNAL = "JU-".$no_jurnal;
				$jurnal->TANGGAL = $tanggal;
				$jurnal->KETERANGAN = "Simpanan Wajib ".$nama;
				
				$jurnal->save();
				
				$jurnal_detail_debet = new JurnalDetail;
				$jurnal_detail_debet->ID_JURNAL = $jurnal->ID_JURNAL;
				$jurnal_detail_debet->ID_AKUN = $otomasi->OTOMASI_DEBET;
				$jurnal_detail_debet->DEBIT_KREDIT = 1;
				$jurnal_detail_debet->NILAI = $jumlah;
				
				$jurnal_detail_debet->save();
				
				$jurnal_detail_kredit = new JurnalDetail;
				$jurnal_detail_kredit->ID_JURNAL = $jurnal->ID_JURNAL;
				$jurnal_detail_kredit->ID_AKUN = $otomasi->OTOMASI_KREDIT;
				$jurnal_detail_kredit->DEBIT_KREDIT = 0;
				$jurnal_detail_kredit->NILAI = $jumlah;
				
				$jurnal_detail_kredit->save();
	}
	
}
